package org.trendit;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.codehaus.groovy.grails.web.json.JSONException;
import org.codehaus.groovy.grails.web.json.JSONObject;

public class HttpHandle {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String url = "https://www.facebook.com/";//&maxwidth=400&maxheight=300&format=json&callback=:callback";
		try {
			String response = getResponseText(url);
			Post det = parseJson(response,url);
			System.out.println(response);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
		}

	}
	public static String getResponseText(String Url) throws IOException {
		String stringUrl = "http://api.embed.ly/1/oembed?key=:519a8c7fdc7b48feaa72f1384c534b44&url="+Url+"&maxwidth=400&maxheight=300&chars=255&format=json";
        StringBuilder response = new StringBuilder();

        URL url = new URL(stringUrl);
        HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();
        if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                BufferedReader input = new BufferedReader(new InputStreamReader(
                                httpconn.getInputStream()), 8192);
                String strLine = null;
                while ((strLine = input.readLine()) != null) {
                        response.append(strLine);
                }
                input.close();
        }
        return response.toString();
}

	public static Post parseJson(String jsonString,String content) {
        JSONObject jObject;
        Post detail = new Post(content);
        try {
                jObject = new JSONObject(jsonString);
               detail.setDescription(jObject.getString("description")) ;
               detail.setAuthor_name1(jObject.getString("author_name"));
               detail.setAuthor_url(jObject.getString("author_url"));
               detail.setHtml(jObject.getString("html"));
               detail.setProvider_name(jObject.getString("provider_name"));
               detail.setProvider_url(jObject.getString("provider_url"));
               detail.setThumbnail_height(jObject.getInt("thumbnail_height"));
               detail.setThumbnail_url(jObject.getString("thumbnail_url"));
               detail.setThumbnail_width(jObject.getInt("thumbnail_width"));
               detail.setTitle(jObject.getString("title"));
               detail.setType(jObject.getString("type"));
               detail.setUrl(jObject.getString("url"));
               detail.setVersion1(jObject.getString("version"));
        } catch (JSONException e) {
                // TODO Auto-generated catch block
              //  e.printStackTrace();
        }
        return detail;

}
}
